package com.ambow.lhd.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpStatus;

import com.ambow.lhd.adapter.ShopListAdapter;
import com.ambow.lhd.api.Api;
import com.ambow.lhd.common.AppException;
import com.ambow.lhd.common.HttpHelper;
import com.ambow.lhd.common.HttpHelper.Callback;
import com.ambow.lhd.common.PageModel;
import com.ambow.lhd.entity.ItemList;
import com.ambow.lhd.entity.Users;
import com.ambow.lhd.service.MyApplication;
import com.ambow.lhd.util.PullDownView;
import com.ambow.lhd.util.PullDownView.UpdateHandler;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
 * 我的发布
 * 
 * @author 林东
 * 
 */
public class MyReleaseListActivity extends Activity implements OnClickListener, UpdateHandler, OnItemClickListener, OnItemLongClickListener{
		
		private MyApplication myApplication;
		Users users;
		Intent intent;
		private String string;
		private int pageNo = 1;
		
		private String condition = "username"; //条件是根据用户名查询   
		private List<ItemList> listDatas = new ArrayList<ItemList>(); 
		private LinearLayout footer; //listView的底部
		private ProgressBar listView_foot_progress; //listView 的底部进度条
		private TextView listView_foot_more; //显示“加载全部”
		private ShopListAdapter adapter; //适配器
		private boolean hasMore = false;
		private int lastItem;
		
		private ImageButton ib_back;//返回
		private TextView tv_login; 
		private TextView tv_type; //类型
		
		private ListView lv_list; //商品列表
		private PullDownView list_pdv; //下拉刷新功能视图类
		
		private Button btn_update; //刷新
		private Button btn_delete; //全部删除
		private Button btn_my_demand; //去求购
		
		private View dialogView; //确认去登陆
		private Dialog dialog; //弹出对话框
		private Button btn_back; //取消登陆按钮
		private Button btn_determine; //确定登陆按钮 
//		private TextView tv_content;
		
		private View delete_dialogView; //确认全部删除
		private Dialog delete_dialog; //弹出对话框
		private Button delete_btn_back; //取消删除全部
		private Button delete_btn_determine; //确定删除全部按
		private TextView delete_tv_content; //对话框内容
		
		private View del_dialogView; //确认单条信息删除
		private Dialog del_dialog; //弹出对话框
		private Button del_btn_back; //取消删除
		private Button del_btn_determine; //确定删除
		private TextView del_tv_content; //对话框内容
		private int index;

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.information_list);
			
			tv_type = (TextView) findViewById(R.id.type_title_tv_type);
			ib_back = (ImageButton) findViewById(R.id.type_title_ib_back);
			tv_login = (TextView) findViewById(R.id.type_title_tv_update);
			
			btn_delete = (Button) findViewById(R.id.information_list_btn_whole);
			btn_my_demand = (Button) findViewById(R.id.information_list_btn_my_school);
			btn_update = (Button) findViewById(R.id.information_list_btn_demand);
			//发布信息列表
			list_pdv = (PullDownView) this.findViewById(R.id.information_list_pdv);
			lv_list = (ListView) list_pdv.findViewById(R.id.information_list_lv_list);
			
			//确认去登陆对话框
			dialogView = getLayoutInflater().inflate(R.layout.alert_dialog, null, false);
//			tv_content = (TextView) dialogView.findViewById(R.id.alert_dialog_tv_content);
			//创建对话框
			dialog = new Dialog(this, R.style.myDialogTheme);
			//对话框事件    
			//注意  必须通过<dialogView.findViewById()>查找布局文件中的指定Id的组件,findViewById()找不到组件
			btn_back = (Button) dialogView.findViewById(R.id.alert_dialog_btn_back);
			btn_determine = (Button) dialogView.findViewById(R.id.alert_dialog_btn_determine);
			
			//注册监听事件
			ib_back.setOnClickListener(this);
			tv_type.setText("我的发布");
			tv_login.setVisibility(View.GONE);
			btn_delete.setOnClickListener(this);
			btn_delete.setText("全部删除");
			btn_my_demand.setOnClickListener(this);
			btn_my_demand.setText("去发布");
			btn_update.setOnClickListener(this);
			btn_update.setText("刷新");
		
			btn_back.setOnClickListener(this); 
			btn_determine.setOnClickListener(this);
			
			myApplication = (MyApplication) this.getApplicationContext();
			myApplication.addActivity(this);
			users = (Users) myApplication.userMap.get("user");
			if (users != null) {  
				//如果用户名不为空则获取用户名
				string = users.getUserName();
				//初始化下拉刷新
				initPullDownView();
				//加载数据
				loadData(pageNo); 
				System.out.println("--------加载我的发布数据--------");
			} else {
				//如果用户未登录则跳到登陆页面
				Toast.makeText(this, "请您先登录", Toast.LENGTH_SHORT).show();
				intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
				MyReleaseListActivity.this.finish();
			}
		}
		
		@Override
		public void onClick(View v) {
			//返回首页
			if(v == ib_back){
				intent = new Intent(this, MainActivity.class);
				this.startActivity(intent);
				this.finish();
			}
			//刷新
			if(v == btn_update){
				list_pdv.startUpdate();
				onUpdate();
			}
			//删除我全部的发布信息
			if(v == btn_delete){
				//警告对话框
				delete_dialogView = getLayoutInflater().inflate(R.layout.alert_dialog, null, false);
				delete_tv_content = (TextView) dialogView.findViewById(R.id.alert_dialog_tv_content);
				//创建对话框
				delete_dialog = new Dialog(this, R.style.myDialogTheme);
				//对话框事件    
				//注意  必须通过<dialogView.findViewById()>查找布局文件中的指定Id的组件,findViewById()找不到组件
				delete_tv_content = (TextView) delete_dialogView.findViewById(R.id.alert_dialog_tv_content);
				delete_btn_back = (Button) delete_dialogView.findViewById(R.id.alert_dialog_btn_back);
				delete_btn_determine = (Button) delete_dialogView.findViewById(R.id.alert_dialog_btn_determine);
				
				delete_tv_content.setText("您确人删除全部吗？\n长按可以删除单条信息");
				delete_btn_back.setOnClickListener(this); 
				delete_btn_determine.setOnClickListener(this);
				//弹出
				delete_dialog.setContentView(delete_dialogView);
				delete_dialog.show();
			}
			//发布物品
			if(v == btn_my_demand){
				 Intent intent = new Intent(this, ReleaseActivity.class);
				 startActivity(intent);
			}
		
			//登陆对话框
			if(v == btn_back){
				//关闭对话框
				dialog.dismiss();
			}
			if(v == btn_determine){
				//确定后跳到登录页面          
				dialog.dismiss();
				Intent intent = new Intent(this,LoginActivity.class);
				this.startActivity(intent);
			}
			//删除对话框
			if(v == delete_btn_back){
				//关闭对话框
				delete_dialog.dismiss();
			}
			if(v == delete_btn_determine){
				//确定后删除全部
				delete_dialog.dismiss();
				System.out.println("------点击确定删除全部------");
				adapter.setItemList(null);
				adapter.notifyDataSetChanged();
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("username", string);
				params.put("shopoid", 0);
			
				HttpHelper.asyncPost(Api.URL + "/second-hand/look_delete.do", params, new Callback() {
					
					@Override
					public void dataLoaded(android.os.Message msg) {
						
						if(HttpStatus.SC_OK != msg.what){
							AppException.http(msg.what).makeToast(MyReleaseListActivity.this);
							return;
						} else {
							Toast.makeText(MyReleaseListActivity.this, "全部删除成功", Toast.LENGTH_SHORT).show();
						}
						
					}
				});
			}
			//长按删除单条信息对话框
			if(v == del_btn_back){
				//关闭对话框
				del_dialog.dismiss();
			}
			if(v == del_btn_determine){
				//确定后删除该条信息
				del_dialog.dismiss();
				int shopid = listDatas.get(index).getShopId();
				listDatas.remove(index);
				adapter.notifyDataSetChanged();
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("username", "");
				params.put("shopoid", shopid);
				HttpHelper.asyncPost(Api.URL + "/second-hand/look_delete.do", params, new Callback() {

					@Override
					public void dataLoaded(Message msg) {
						if(HttpStatus.SC_OK != msg.what){
							AppException.http(msg.what).makeToast(MyReleaseListActivity.this);
							return;
						} else {
							Toast.makeText(MyReleaseListActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
						}
					}
				});
			}
		}
		
		//初始化下拉刷新
		private void initPullDownView() {
			// 设置下拉刷新处理器
			list_pdv.setUpdateHandler(this);
			//点击查看物品详情
			lv_list.setOnItemClickListener(this);
			lv_list.setOnItemLongClickListener(this);
			//初始化底部视图
			this.footer = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_footer, null);
			listView_foot_progress = (ProgressBar) findViewById(R.id.listview_foot_progress);
			listView_foot_more = (TextView) findViewById(R.id.listview_foot_more);
			
			lv_list.addFooterView(footer); //添加底部视图必须在setAdapter前
			lv_list.setFooterDividersEnabled(false);
			
			///////////////////////////////分清发布与求购/////////////////////////////
			adapter = new ShopListAdapter(this);
			lv_list.setAdapter(adapter);
			//设置滚动侦听器
			lv_list.setOnScrollListener(new AbsListView.OnScrollListener() {
				
				@Override
				public void onScrollStateChanged(AbsListView view, int scrollState) {
					//数据为空
					if(listDatas.isEmpty()){
						return;
					}
					// 判断是否滚动到底部
					if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE 
							&& lastItem == adapter.getCount()){
						if (hasMore) {
							listView_foot_progress.setVisibility(View.VISIBLE);
							listView_foot_more.setText("加载中...");
							loadData(++pageNo);
						}
					}
				}
				
				@Override      //0.view  1.总项目数  2. 可见项目数  3. 第一个可见项
				public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
					lastItem = firstVisibleItem + visibleItemCount - 1;
				}
			});	
		}
		
		@Override  //点击查看物品详情
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

			if(position == lv_list.getCount()-1){
				System.out.println("-----myRelease---position-------"+position);
			}else{
				ItemList itemList = listDatas.get(position);
				Bundle data = new Bundle();
				data.putSerializable("shopinfo", itemList);
				Intent intent = new Intent(this, DemandInfoActivity.class);
				intent.putExtras(data);
				this.startActivity(intent);
			}
		}
		
		@Override  //长按删除该条信息
		public boolean onItemLongClick(AdapterView<?> parent, View v,int position, long id) {
			if(position == lv_list.getCount()-1){
				return false;
			}
			index = position;
			//警告对话框
			del_dialogView = getLayoutInflater().inflate(R.layout.alert_dialog, null, false);
			del_tv_content = (TextView) dialogView.findViewById(R.id.alert_dialog_tv_content);
			//创建对话框
			del_dialog = new Dialog(this, R.style.myDialogTheme);
			//对话框事件    
			//注意  必须通过<dialogView.findViewById()>查找布局文件中的指定Id的组件,findViewById()找不到组件
			del_tv_content = (TextView) del_dialogView.findViewById(R.id.alert_dialog_tv_content);
			del_btn_back = (Button) del_dialogView.findViewById(R.id.alert_dialog_btn_back);
			del_btn_determine = (Button) del_dialogView.findViewById(R.id.alert_dialog_btn_determine);
			
			del_tv_content.setText("您确认删除吗？删除后将不能恢复！");
			del_btn_back.setOnClickListener(this); 
			del_btn_determine.setOnClickListener(this);
			//弹出
			del_dialog.setContentView(del_dialogView);
			del_dialog.show();
			
			return false;
		}
		// 回调方法
		public void onUpdate() {
			pageNo = 1;
			lv_list.setSelection(0);
			loadData(pageNo);
		}

		//加载数据
			public void loadData(int pn) {
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("pageNo", pn);
				params.put("value", string);
				params.put("condition", condition);
				params.put("school", "");
				//listView底部设置
				if(pageNo == 1){
					listDatas.clear();
					//是否可见
					footer.setVisibility(View.GONE);
					//设置页脚分频器启用  <--需要底部分割线设置方法为：android:footerDividersEnabled="true"
					lv_list.setFooterDividersEnabled(false);
				}else {
					footer.setVisibility(View.VISIBLE);
					lv_list.setFooterDividersEnabled(true);
				}
				HttpHelper.asyncPost(Api.URL + "/second-hand/shop_info.do", params, new Callback() {
					
					@Override
					public void dataLoaded(Message msg) {
						
						//不显示底部
						footer.setVisibility(View.GONE);
						if(HttpStatus.SC_OK != msg.what){
							AppException.http(msg.what).makeToast(MyReleaseListActivity.this);
							list_pdv.endUpdate();
							return;
						}
						String json = (String) msg.obj;
						Log.v("---------我的发布信息----------", json);
						PageModel<ItemList> pm = PageModel.jsonConvert(json);
						listDatas.addAll(pm.getData());
						adapter.setItemList(listDatas);
						/**
						 * notifyDataSetChanged方法
						 * 通过一个外部的方法控制如果适配器的内容改变时需要强制调用getView来刷新每个Item的内容,
						 * 可以实现动态的刷新列表的功能。
						 * endUpdate方法
						 * 它们在操纵基础数据或控件属性时取消了控件的重新绘制。
						 * 通过使用BeginUpdate 和 EndUpdate 方法，您可以对控件进行重大更改，
						 * 并且避免在应用这些更改时让控件经常重新绘制自身。
						 * 此类重新绘制会导致性能显著降低，并且用户界面闪烁且不反应。
						 */
						adapter.notifyDataSetChanged();
						list_pdv.endUpdate();
						
						if (pageNo < pm.getPageCount()) {
							hasMore = true;
						}else {
							hasMore = false;
							System.out.println("-----------??????1-----------");
//							footer.setVisibility(View.VISIBLE); //可见
//							listView_foot_progress.setVisibility(View.INVISIBLE); //不可见
//							listview_foot_more.setText("已加载全部信息");
							System.out.println("-----------??????2-----------");
						}
					}
				});
			}
	}